package com.itheima.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.OrderService;
import com.itheima.contant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderInfoVCS;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private MemberDao memberDao;

    @Override
    public Result memoryOrderInfo(Map map) {
        //TODO : 前台传回的结果的格式    身份证号 ：idCard
        //      {setmealId=12, idCard=1, sex=1, name=1, validateCode=1, telephone=11, orderDate=2019-09-17}

        /*处理预约信息*/
        //1、查看所选日期是否可预约
        String orderDate = map.get("orderDate").toString();
        Date date = DateUtil.parse(orderDate, "yyyy-MM-dd");
        /*查询预约设置信息*/
        OrderSetting orderSetting = orderDao.queryOrderSetting(orderDate);
        if (orderSetting == null) {
            return Result.error("当前日期不可预约");
        }

        //2、如果当天预约人数已满，则不能再预约
        Map<String, Integer> orderMap = orderDao.queryOrderPeopleNumber(orderDate);


        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (number <= reservations) {
            return Result.error(MessageConstant.ORDER_FULL);
        }


        //3、如果不是会员，直接注册为会员再进行预约，如果是会员则直接预约
        String telephone = (String) map.get("telephone");
        Member member = orderDao.queryMemberById(telephone);


        if (member == null){
            member = new Member();
            member.setRegTime(new Date());
            member.setSex((String) map.get("sex"));
            member.setIdCard((String) map.get("idCard"));
            member.setPhoneNumber(telephone);
            member.setName((String) map.get("name"));
            /*添加新会员,这里让会员id进行回显，后面要用到*/
            orderDao.addMember(member);
        }else{
            map.put("id",member.getId());
            /*是会员，就更新会员信息*/
            memberDao.updateMember(map);
        }


        //4、不能重复预约,跟据会员id来判断
        // 同一个会员在同一天预约同一个套餐就算是重复预约
        String setmealId = String.valueOf(map.get("setmealId")) ;
        Order order = orderDao.notRepeatOrder(member.getId(),orderDate,setmealId);
        if (order != null){
            return Result.error(MessageConstant.HAS_ORDERED);
        }

         //5、预约
        //   并让预约人数加一
        order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(date);
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setOrderType((String) map.get("orderType"));
        order.setSetmealId(Integer.parseInt(setmealId));

        /*此处设置id回显，此id最终要回显到页面的url中，供预约成功页面使用*/
        orderDao.addOrder(order);

        /*取出原本的版本号*/
        Integer version = orderSetting.getVersion();

        /*TODO : 加乐观锁 更新预约设置表*/       /*防止字段值为 null*/
        Integer integer = orderDao.updateOrderSetting(orderSetting.getReservations() + 1, orderSetting.getId(), version);
        if (integer == 0){
            return null;
        }

        /*传回预约表id*/
        return Result.success(MessageConstant.ORDER_SUCCESS,order.getId());
    }

    /*电话预约*/
    @Override
    public Result phoneOrder(OrderInfoVCS orderInfoVCS) {
        //TODO : 前台传回的结果的格式    身份证号 ：idCard
        //      {setmealId=12, idCard=1, sex=1, name=1, validateCode=1, telephone=11, orderDate=2019-09-17}

        /*处理预约信息*/
        //1、查看所选日期是否可预约
        String orderDate = orderInfoVCS.getOrderDate() ;
        Date date = DateUtil.parse(orderDate, "yyyy-MM-dd");
        /*查询预约设置信息*/
        OrderSetting orderSetting = orderDao.queryOrderSetting(orderDate);
        if (orderSetting == null) {
            return Result.error("当前日期不可预约");
        }

        //2、如果当天预约人数已满，则不能再预约
        Map<String, Integer> orderMap = orderDao.queryOrderPeopleNumber(orderDate);


        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (number <= reservations) {
            return Result.error(MessageConstant.ORDER_FULL);
        }


        //3、如果不是会员，直接注册为会员再进行预约，如果是会员则直接预约
        String telephone = orderInfoVCS.getTelephone();
        Member member = orderDao.queryMemberById(telephone);


        if (member == null){
            member = new Member();
            member.setRegTime(new Date());
            member.setSex(orderInfoVCS.getSex().toString());
            member.setPhoneNumber(telephone);
            member.setName(orderInfoVCS.getName());
            /*添加新会员,这里让会员id进行回显，后面要用到*/
            orderDao.addMember(member);
        }else{

            orderInfoVCS.setMemberId(member.getId());
            /*是会员，就更新会员信息*/
            memberDao.updateMember(orderInfoVCS);
        }


        //4、不能重复预约,跟据会员id来判断
        // 同一个会员在同一天预约同一个套餐就算是重复预约
        List<Integer> setmealIds = orderInfoVCS.getSetmealIds();
        if (setmealIds != null && setmealIds.size() > 0){

            for (Integer setmealId : setmealIds) {
                Order order = orderDao.notRepeatOrder(member.getId(),orderDate,setmealId.toString());
                if (order != null){
                    return Result.error(MessageConstant.HAS_ORDERED);
                }
                //5、预约
                //   并让预约人数加一


                order = new Order();
                order.setMemberId(member.getId());
                order.setOrderDate(date);
                order.setOrderStatus(Order.ORDERSTATUS_NO);
                order.setOrderType(orderInfoVCS.getOrderType());
                order.setSetmealId(setmealId);
                /*此处设置id回显，此id最终要回显到页面的url中，供预约成功页面使用*/
                orderDao.addOrder(order);
                /*取出原本的版本号*/
                Integer version = orderSetting.getVersion();

                /*TODO : 加乐观锁 更新预约设置表*/       /*防止字段值为 null*/
                Integer integer = orderDao.updateOrderSetting(orderSetting.getReservations() + 1, orderSetting.getId(), version);
                if (integer == 0){
                    return null;
                }
            }
        }

        return Result.success("");
    }


    @Override
    public Map<String, Object> queryOrderInfo(Integer id) {

         /*前端将预约表id传回来
        返回给前端的数据格式
            {data.member}
            {data.setmeal}
            {data.orderDate}
            {data.orderType}
        * */
        Map<String, Object> map = new HashMap<>();


        Order order = orderDao.queryOrderInfo(id);

        /*查询体检人的名字*/
        Integer memberId = order.getMemberId();
        String name = orderDao.queryMemberName(memberId);
        map.put("member",name);

        /*查询套餐内容*/
        String setmealContent =  orderDao.querySetmealContent(order.getSetmealId());
        map.put("setmeal",setmealContent);

        String format = DateUtil.format(order.getOrderDate(), "yyyy月MM月dd日");


        map.put("orderDate",format);
        map.put("orderType",order.getOrderType());

        return map;
    }


}
